<template>
  <Dialog ref="dialog" width="800" :title="title">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      label-width="auto"
      :rules="rules"
      status-icon
    >
      <el-row class="el-col-24">
        <el-form-item class="form_item el-col-10" label="机构名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入机构名称"
            clearable
          />
        </el-form-item>
        <el-form-item class="form_item el-col-10" label="联系人" prop="user">
          <el-input
            v-model="ruleForm.user"
            placeholder="请输入联系人"
            clearable
          />
        </el-form-item>
        <el-form-item class="form_item el-col-10" label="电话" prop="mobile">
          <el-input
            v-model="ruleForm.mobile"
            placeholder="请输入电话"
            clearable
          />
        </el-form-item>
        <el-form-item
          class="form_item el-col-10"
          label="应用"
          prop="application"
        >
          <el-select
            :multiple="currentItem"
            v-model="ruleForm.application"
            placeholder="请输入应用"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @click.native="handleSelectChange(item)"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="form_item el-col-10" label="省份" prop="pids">
          <el-select
            collapse-tags
            v-model="ruleForm.pids"
            multiple
            placeholder="请输入省份"
            size="large"
            style="width: 240px"
            @change="handleChange"
          >
            <!-- 全国选项 -->
            <el-option :key="-1" :label="'全国'" :value="-1" />
            <!-- 其他选项 -->
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.provinceName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="form_item el-col-10"
          label="默认省份"
          prop="defaultPid"
        >
          <el-select
            v-model="ruleForm.defaultPid"
            placeholder="请默认选择一个省份"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in childData"
              :key="item.id"
              :label="item.provinceName"
              :value="Number(item.id)"
            />
          </el-select>
        </el-form-item>
      </el-row>
    </el-form>
    <el-divider />
    <div class="right">
      <el-button class="height40" @click="closeChange">取消</el-button>
      <el-button type="primary" class="height40" @click="submit"
        >提交</el-button
      >
    </div>
  </Dialog>
</template>
<script setup>
import Dialog from '@/components/Dialog/Dialog.vue';
import { ElMessage } from 'element-plus';
import {
  editCustomer,
  addStore,
  //  getAppList
} from '@/api/appv2/appv2';
import { ref, onMounted } from 'vue';
const props = defineProps({
  optionsDataList: {
    type: Array,
    default: () => [],
  },
  provinceList: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(['getCustomer']);

let { proxy } = getCurrentInstance();
const options = ref([]);
const currentItem = ref(null);
const customerInfo = ref(undefined);
const is_tags = ref(true);
const childId = ref([]);
const childData = ref([]);
const ruleForm = ref({
  name: '',
  user: '',
  mobile: '',
  application: [],
  pids: [],
  defaultPid: [],
});
const dialog = ref(null);
const title = ref('新增机构');
const rules = {
  name: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入目录名称',
    },
  ],
  user: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入联系人',
    },
  ],
  mobile: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入电话',
    },
  ],
  application: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入应用',
    },
  ],
  pids: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入省份',
    },
  ],
  defaultPid: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入一个省份',
    },
  ],
};

// 提交
function submit() {
  proxy.$refs.ruleFormRef.validate((valid) => {
    if (valid) {
      if (title.value == '新增机构') {
        ruleForm.value.pids = ruleForm.value.pids.join(',');
        addStore({
          ...ruleForm.value,
        }).then((res) => {
          if (res.code === 20000) {
            ElMessage.success('添加成功');
            dialog.value.closeChange();
            emit('getCustomer');
          }
        });
      } else {
        ruleForm.value.application = currentItem.value
          ? ruleForm.value.application.join(',')
          : ruleForm.value.application;
        ruleForm.value.pids = Array.isArray(ruleForm.value.pids)
          ? ruleForm.value.pids.join(',')
          : ruleForm.value.pids;
        editCustomer({
          ...ruleForm.value,
          id: customerInfo.value.id,
        }).then(() => {
          ElMessage.success('修改成功');
          dialog.value.closeChange();
          emit('getCustomer');
        });
      }
    } else {
      ElMessage.warning('请完善信息');
    }
  });
}
// 打开弹窗
function openchange(val) {
  if (val != undefined) {
    title.value = '编辑机构';
    customerInfo.value = val;
    childData.value = props.provinceList.filter((item) =>
      val.pids.includes(item.id)
    );
    ruleForm.value = {
      name: val.name,
      user: val.user,
      mobile: val.mobile,
      application:
        val.appIds && currentItem.value
          ? val.appIds.split(',').map(Number)
          : val.appIds != null
            ? Number(val.appIds)
            : '',
      pids: val.pids ? val.pids.split(',').map(Number) : [],
      defaultPid: val.defaultPid,
    };
    console.log(ruleForm.value, 33333);
  } else {
    title.value = '新增机构';
    ruleForm.value = {};
  }
  dialog.value.openChange();
}
// 关闭弹窗
function closeChange() {
  dialog.value.closeChange();

  Object.assign(ruleForm.value, {});
}
// 判断是否为主应用
const handleSelectChange = (item) => {
  item.is_must != 1 ? (currentItem.value = true) : (currentItem.value = false);
};

// 处理选中逻辑
const handleChange = (value) => {
  if (value.includes(-1)) {
    if (is_tags.value) {
      childData.value = [];
      // 如果选中了“全国”，选中除“全国”以外的所有选项
      ruleForm.value.pids = props.provinceList.map((item) => item.id);
      childId.value = ruleForm.value.pids;
      // 筛选出匹配 id 的数据
      childData.value = props.provinceList.filter((item) =>
        childId.value.includes(item.id)
      );
      ruleForm.value.defaultPid = value[0] == -1 ? '' : value[0];
      is_tags.value = !is_tags.value;
    } else {
      childData.value = [];
      ruleForm.value.pids = [];
      ruleForm.value.defaultPid = '';
      is_tags.value = !is_tags.value;
    }
  } else {
    childData.value = [];
    // 如果手动取消“全国”，移除“全国”选项
    ruleForm.value.pids = value.filter((id) => id !== -1);
    childId.value = ruleForm.value.pids;
    // 筛选出匹配 id 的数据
    childData.value = props.provinceList.filter((item) =>
      childId.value.includes(item.id)
    );
    ruleForm.value.defaultPid = value[0];
  }
};
// 添加应用
onMounted(() => {
  const res = props.optionsDataList.filter((item) => (item.is_must = 1));
  options.value = res;
});
defineExpose({
  openchange,
});
</script>
<style>
.form_item {
  margin-bottom: 20px !important;
  margin-right: 20px;
}

.right {
  margin-left: 40px;
}
</style>
